package com.chen.pay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.chen.model.entity.pay.PaymentInfo;
import com.chen.model.vo.common.Result;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.pay.mapper.PaymentInfoMapper;
import com.chen.pay.properties.AlipayProperties;
import com.chen.pay.service.PayService;
import com.chen.pay.service.PaymentInfoService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author cgj
 * @date 5/4/25 9:09 AM
 */
@RestController
@RequestMapping("/api/order/alipay")
public class AlipayController {
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private PayService payService;
    @Autowired
    private PaymentInfoService paymentInfoService;


    // 支付成功后支付宝要给这个地址发送请求: http://127.0.0.1:8500/api/order/alipay/callback/notify
    @RequestMapping("/callback/notify")
    @SneakyThrows
    public String alipayNotify(@RequestParam Map<String, String> paramsMap) {
        System.out.println(paramsMap);
        System.out.println("aaaaaa");

        //验证码签名
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipayProperties.getAlipayPublicKey(), alipayProperties.charset, alipayProperties.sign_type); //调用SDK验证签名
        if (signVerified) {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //获取数据继续验证
            String outTradeNo = paramsMap.get("out_trade_no");
            String totalAmount = paramsMap.get("total_amount");
            String appId = paramsMap.get("app_id");
            PaymentInfo paymentInfo = paymentInfoService.selectPaymentInfoByOrderNo(outTradeNo);
            if (paymentInfo != null
                    && alipayProperties.getAppId().equals(appId)
                    && new BigDecimal("0.01").compareTo(new BigDecimal(totalAmount)) == 0) {

                String tradeStatus = paramsMap.get("trade_status");
                //只有着两种状态支付宝才会认为支付成功
                if("TRADE_SUCCESS".equals(tradeStatus)||"TRADE_FINISHED".equals(tradeStatus)){
                    //二次验证成功,处理支付成功的业务
                    //更新订单状态
                      paymentInfoService.updatePaymentInfo(paramsMap,outTradeNo);
                    return "success"; //支付宝只认success
                }
            }

        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
        return "error";
    }

    //  http://localhost:8500/api/order/alipay/submitAlipay/1746320939633
    @GetMapping("/submitAlipay/{orderNo}")
    public Result<String> submitAlipay(@PathVariable String orderNo) {
        // 支付宝支付
        String form = payService.submitAlipay(orderNo);//返回一个表单
        return Result.build(form, ResultCodeEnum.SUCCESS);
    }
}
